package com.soulkun.smarthome.ui.main.personal

import android.Manifest
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.view.Gravity
import android.view.View
import android.widget.PopupMenu
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.navGraphViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.maps.MapsInitializer
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.google.android.material.snackbar.Snackbar
import com.soulkun.smarthome.R
import com.soulkun.smarthome.databinding.AppFragmentMainPersonalFamilySettingBinding
import com.soulkun.smarthome.databinding.AppRecycleItemMainPersonalFamilySettingFamilyInvitationListBinding
import com.soulkun.smarthome.databinding.AppRecycleItemMainPersonalFamilySettingFamilyUserListBinding
import com.soulkun.smarthome.logic.Constant
import com.soulkun.smarthome.ui.main.home.dialog.AppMainHomeSpeechRecognitionDialog
import com.soulkun.smarthome.ui.main.personal.adapter.AppMainPersonalFamilySettingFamilyInvitationListAdapter
import com.soulkun.smarthome.ui.main.personal.adapter.AppMainPersonalFamilySettingFamilyUserListAdapter
import com.soulkun.smarthome.ui.main.personal.dialog.AppMainPersonalFamilyDeleteDialog
import com.soulkun.smarthome.ui.main.personal.dialog.AppMainPersonalFamilyMemberDeleteDialog
import com.soulkun.smarthome.ui.main.personal.dialog.AppMainPersonalFamilyRenameDialog
import com.soulkun.smarthome.ui.main.personal.dialog.AppMainPersonalFamilyRoleSetDialog
import com.soulkun.smarthome.ui.main.personal.viewmodel.AppMainPersonalFamilySettingSharedViewModel
import com.soulkun.smarthome.ui.main.personal.viewmodel.AppMainPersonalFamilySettingViewModel
import soulkun.library.mvvm.component.BaseDataBindingFragment
import soulkun.library.utils.logE
import soulkun.library.utils.navigateSafe
import soulkun.library.utils.permission.PermissionUtils
import soulkun.library.utils.screen.ScreenUtils
import soulkun.library.utils.toast

class AppMainPersonalFamilySettingFragment :
    BaseDataBindingFragment<AppFragmentMainPersonalFamilySettingBinding>() {

    private val sharedViewModel by navGraphViewModels<AppMainPersonalFamilySettingSharedViewModel>(R.id.app_navigation_main_personal_family_setting)
    private val viewModel by viewModels<AppMainPersonalFamilySettingViewModel> { defaultViewModelProviderFactory }

    private lateinit var geocodeSearch: GeocodeSearch

    private val setRoleDialog by lazy {
        AppMainPersonalFamilyRoleSetDialog(viewModel)
    }
    private val deleteMemberDialog by lazy {
        AppMainPersonalFamilyMemberDeleteDialog(viewModel)
    }
    private val familyRenameDialog by lazy {
        AppMainPersonalFamilyRenameDialog(viewModel)
    }
    private val deleteFamilyDialog by lazy {
        AppMainPersonalFamilyDeleteDialog(viewModel)
    }
    private val userAdapter by lazy {
        AppMainPersonalFamilySettingFamilyUserListAdapter(
            mContext,
            viewModel.familyMemberList
        ) { binding ->
            View.OnClickListener {
                viewModel.selectFamilyUserLiveData.value =
                    (binding as AppRecycleItemMainPersonalFamilySettingFamilyUserListBinding).familyMemberVO
                val popupMenu = PopupMenu(mContext, it)
                val menuInflater = popupMenu.menuInflater
                menuInflater.inflate(R.menu.app_menu_main_member, popupMenu.menu)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    popupMenu.gravity = Gravity.END
                }
                popupMenu.setOnMenuItemClickListener { menu ->
                    when (menu.itemId) {
                        R.id.app_member_set -> {
                            setRoleDialog.show(childFragmentManager, "SetRoleDialog")
                        }
                        R.id.app_member_delete -> {
                            deleteMemberDialog.show(childFragmentManager, "DeleteMemberDialog")
                        }
                    }
                    false
                }
                popupMenu.show()
            }
        }
    }
    private val invitationAdapter by lazy {
        AppMainPersonalFamilySettingFamilyInvitationListAdapter(
            mContext,
            viewModel.familyInvitationList
        ) { binding ->
            View.OnClickListener {
                val clipboardManager =
                    mActivity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                val mClipData = ClipData.newPlainText(
                    "Name",
                    (binding as AppRecycleItemMainPersonalFamilySettingFamilyInvitationListBinding).familyInvitationModel!!.code
                )
                clipboardManager.setPrimaryClip(mClipData)
                "已复制到剪贴板".toast()
            }
        }
    }

    override fun setLayout(): Int {
        return R.layout.app_fragment_main_personal_family_setting
    }

    override fun initView() {
        ScreenUtils.setViewFitSystemWindows(requireDataBinding().root)
        requireDataBinding().rvMainPersonalFamilySettingListMember.run {
            layoutManager = LinearLayoutManager(mContext)
            adapter = userAdapter
        }
        requireDataBinding().rvMainPersonalFamilySettingListInvitation.run {
            layoutManager = LinearLayoutManager(mContext)
            adapter = invitationAdapter
        }
    }

    override fun initData() {
        geocodeSearch = GeocodeSearch(mContext)
        requireDataBinding().lifecycleOwner = viewLifecycleOwner
        requireDataBinding().viewModel = viewModel
        requireDataBinding().onClickListener = View.OnClickListener {
            when (it.id) {
                R.id.iv_main_personal_family_setting_icon_back -> {
                    findNavController().navigateUp()
                }
                R.id.tv_main_personal_family_setting_text_family_name, R.id.iv_main_personal_family_setting_icon_family_name_enter -> {
                    familyRenameDialog.show(childFragmentManager, "FamilyRenameDialog")
                }
                R.id.tv_main_personal_family_setting_text_family_location, R.id.iv_main_personal_family_setting_icon_family_location_enter -> {
                    if (PermissionUtils.fragmentCheckPermissionList(
                            this,
                            mContext,
                            listOf<String>(
                                Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.READ_PHONE_STATE
                            ),
                            Constant.PERMISSION_REQUEST_LOCATION
                        )
                    ) {
                        sharedViewModel.familyId = viewModel.familyIdLiveData.value!!
                        findNavController().navigateSafe(
                            R.id.action_appMainPersonalFamilySettingFragment_to_appMainPersonalFamilyLocationFragment,
                            R.id.appMainPersonalFamilySettingFragment
                        )
                    }
                }
                R.id.tv_main_personal_family_setting_text_family_room, R.id.iv_main_personal_family_setting_icon_family_room_enter -> {
                    sharedViewModel.familyId = viewModel.familyIdLiveData.value!!
                    sharedViewModel.familyRoomList.clear()
                    sharedViewModel.familyRoomList.addAll(viewModel.familyRoomList)
                    findNavController().navigateSafe(
                        R.id.action_appMainPersonalFamilySettingFragment_to_appMainPersonalFamilyRoomFragment,
                        R.id.appMainPersonalFamilySettingFragment
                    )
                }
                R.id.tv_main_personal_family_setting_text_add_member -> {
                    viewModel.addMember().observe(viewLifecycleOwner) { result ->
                        val result = result.getOrNull()
                        if (result != null) {
                            result.statusMessage.toast()
                            viewModel.familyInvitationList.add(result.data)
                        }
                    }
                }
                R.id.tv_main_personal_family_setting_text_delete_family -> {
                    deleteFamilyDialog.show(childFragmentManager, "DeleteFamilyDialog")
                }
            }
        }
        viewModel.getFamilyDetailInfo()
    }

    override fun initListener() {
        geocodeSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
            // 经纬度转位置名称
            override fun onRegeocodeSearched(result: RegeocodeResult?, rCode: Int) {
                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (result != null && result.regeocodeAddress != null && result.regeocodeAddress.formatAddress != null) {
                        val locationText = result.regeocodeAddress.formatAddress
                        requireDataBinding().tvMainPersonalFamilySettingTextFamilyLocation.text =
                            locationText
                    }
                }
            }

            override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
            }
        })
        viewModel.familyLocationLiveData.observe(viewLifecycleOwner) {
            geocodeSearch.getFromLocationAsyn(
                RegeocodeQuery(
                    LatLonPoint(
                        it.latitude,
                        it.longitude
                    ), 100f, GeocodeSearch.AMAP
                )
            )
        }
    }

    override fun doOnCreate() {
        viewModel.familyIdLiveData.value = arguments?.getLong("familyId")!!
        MapsInitializer.updatePrivacyShow(mContext, true, true)
        MapsInitializer.updatePrivacyAgree(mContext, true)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            Constant.PERMISSION_REQUEST_LOCATION -> {
                for (i in permissions.indices) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !shouldShowRequestPermissionRationale(
                                permissions[i]
                            )
                        ) { //如果用户拒接并选择不再询问
                            Snackbar.make(
                                requireDataBinding().root,
                                "请授权位置和电话权限，否则无法设置家庭位置",
                                Snackbar.LENGTH_LONG
                            )
                                .setAction(
                                    "前去设置"
                                ) { PermissionUtils.goToPermissionSettingPage(mContext) }
                                .show()
                            return
                        }
                    }
                }
                sharedViewModel.familyId = viewModel.familyIdLiveData.value!!
                findNavController().navigateSafe(
                    R.id.action_appMainPersonalFamilySettingFragment_to_appMainPersonalFamilyLocationFragment,
                    R.id.appMainPersonalFamilySettingFragment
                )
            }
        }
    }

}